package com.sara.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class LoginFilter extends AbstractFilter {

    private List<String> uriList = null;


    @Override
    public void init(FilterConfig config) throws ServletException {
        String paths = config.getInitParameter("paths");
        String[] uris = paths.split(",");
        uriList = Arrays.asList(uris);


    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) resp;

        String requestURI = request.getRequestURI();

        if(isFilter(requestURI)){
            if(request.getSession().getAttribute("admin") == null){
                response.sendRedirect("/login?path=" + requestURI);
            }else {
                chain.doFilter(request,response);
            }

        }else {
            chain.doFilter(request,response);
        }

    }

    private boolean isFilter(String requestURI) {
        if(requestURI == null){
            return false;
        }
        for (String uri : uriList){
            if(requestURI.startsWith(uri)){
                return true;
            }
        }
        return  false;
    }
}
